package com.sun.showcase.controller.app.mall;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sun.showcase.biz.basic.utils.FtpClientConstants;
import com.sun.showcase.biz.exception.BusinessException;
import com.sun.showcase.biz.mall.service.MemberService;
import com.sun.showcase.biz.mall.service.PosterService;
import com.sun.showcase.biz.sms.SmsComponent;
import com.sun.showcase.client.domain.mall.Member;
import com.sun.showcase.client.domain.mall.Poster;
import com.sun.showcase.client.query.mall.MemberQuery;
import com.sun.showcase.conf.wx.miniapp.WxMaConfiguration;
import com.sun.showcase.conf.wx.miniapp.WxMaProperties;
import com.sun.showcase.pojo.Result;
import com.sun.showcase.utils.ExecuteResult;
import com.sun.showcase.utils.FileUpload;
import com.sun.showcase.utils.SpringApplicationContextHolder;
import com.vdurmont.emoji.EmojiParser;

import cn.binarywang.wx.miniapp.api.WxMaService;
@CrossOrigin
@RestController("appMemberController")
@RequestMapping(value="/app/member") 
public class MemberController{
	
	@Autowired
	private MemberService memberService;
	@Autowired
	private SmsComponent smsComponent;
	@Autowired
	private WxMaProperties properties;
	@Autowired
	private PosterService posterService;
	//添加会员
	@RequestMapping(value="regist")
	public Result regist(MemberQuery pojo,String code,BindingResult bindingResult) {
		
		Result result = new Result();
		
		if(StringUtils.isBlank(code))
			throw new BusinessException("短信码不能为空！");
		
		ExecuteResult<String> ex = smsComponent.validate(pojo.getPhone(), "1", code);
		
		if(!ex.isSuccess())
			throw new BusinessException(ex.getErrorMessages().get(0).toString());
		
		
		//验证
		if(bindingResult.hasErrors()) 
			throw new BusinessException(bindingResult.getFieldError().getDefaultMessage());
		
		MemberQuery query = new MemberQuery();
		
		BeanUtils.copyProperties(pojo, query);
		//删除表符号
		query.setNickName(EmojiParser.removeAllEmojis(query.getNickName()));
		//query.setNickName((query.getNickName()));
		
		if(StringUtils.isNotBlank(query.getHeadImage())) {
	    	try {
				String imagePath = FileUpload.uploadLocal3("picture", query.getHeadImage());
				FtpClientConstants ftpClientConstants=(FtpClientConstants)SpringApplicationContextHolder.getBean("ftpClientConstants");
				query.setHeadImage(ftpClientConstants.getPrefixUrl()+ imagePath);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Member t = memberService.save(query);
		
		result.setSuccess(true);
		result.setData(t);
		result.setMsg("添加成功！");
		
		return result;
	}
	
	//查询openID 
	@RequestMapping(value="find/openid")
	public Result findByOpenid(String openid) {
		
		Result result = new Result();
		
		//验证
		if(StringUtils.isBlank(openid)) 
			throw new BusinessException("未检测到openid");
		
		Member t = new Member();
		
		MemberQuery q = new MemberQuery();
		
		q.setOpenid(openid);
		
		List<MemberQuery> l = this.memberService.listAll(q);
		
		if(null!=l && l.size()>0) {
			
			MemberQuery m  = l.get(0);
			
			BeanUtils.copyProperties(m, t);
		}else
			throw new BusinessException("");
		
		
		result.setSuccess(true);
		result.setData(t);
		
		return result;
	}
	
	//会员信息
	@RequestMapping(value="show")
	public Result list(MemberQuery query) {
		
		if(StringUtils.isBlank(query.getId()))
			throw new BusinessException("未检测到会员ID！");
		
		Result result = new Result();
		
		MemberQuery q = new MemberQuery();
		
		Member t = memberService.get(query.getId());
		
		BeanUtils.copyProperties(t, q);
		
		result.setData(q);
		result.setSuccess(true);
		
		return result;
		
	}
	//会员信息
	@RequestMapping(value="registWithPhoneAndPwd")
	public Result registWithPhoneAndPwd(MemberQuery query) {
		
		ExecuteResult<Member> res = memberService.registWithPhoneAndPwd(query);
		Result result = new Result();
		result.setSuccess(res.isSuccess());
		if(res.isSuccess()) {
			result.setData(res.getResult());
		}else {
			result.setMsg(res.getErrorMessages().get(0));
		}
		
		return result;
		
	}
	@RequestMapping(value="loginWithPhoneAndPwd")
	public Result loginWithPhoneAndPwd(MemberQuery query) {
		
		ExecuteResult<Member> res = memberService.loginWithPhoneAndPwd(query);
		Result result = new Result();
		result.setSuccess(res.isSuccess());
		if(res.isSuccess()) {
			result.setData(res.getResult());
		}else {
			result.setMsg(res.getErrorMessages().get(0));
		}
		
		return result;
		
	}
	
	@RequestMapping(value="getQrCode")
	public Result getQrCode(String id) {
		Result result = new Result();
		
		Member mem = memberService.get(id);
		Poster p = posterService.get();
		if(mem == null) {
			result.setSuccess(false);
			result.setMsg("无效用户");
			return result;
		}
		if(StringUtils.isNotBlank(mem.getQrcode())) {
			result.setSuccess(true);
			p.setQrcode(mem.getQrcode());
			result.setData(p);
			return result;
		}else {
			final WxMaService wxService = WxMaConfiguration.getMaService(properties.getConfigs().get(0).getAppid());
			try {
				File f;
				try {
					f = wxService.getQrcodeService().createWxaCodeUnlimit(id, "pages/public/login");
				} catch (Exception e) {
					f = wxService.getQrcodeService().createWxaCodeUnlimit(id, null);
				}
				FtpClientConstants ftpClientConstants=(FtpClientConstants)SpringApplicationContextHolder.getBean("ftpClientConstants");
				String imagePath = FileUpload.uploadLocal2("picture", f);
				String qrCode = ftpClientConstants.getPrefixUrl()+ imagePath;
				MemberQuery up = new MemberQuery();
				up.getSearchMap().put("id", id);
				up.setQrcode(qrCode);
				memberService.updatePart(up);
				p.setQrcode(qrCode);
				result.setSuccess(true);
				result.setData(p);
			} catch (Exception e) {
				e.printStackTrace();
				result.setSuccess(false);
				result.setMsg("获取二维码失败，请稍后重试！");
				return result;
			}
		}
		return result;
		
	}
}
